# D:\dazuoye\app\views\task2_campaigns.py

from flask import Blueprint, jsonify
from app.data_loader import campaign_data # 从数据模块导入数据

# 1. 创建蓝图对象
task2_bp = Blueprint('task2_campaigns', __name__)

# 2. 在蓝图上注册路由
@task2_bp.route('/api/marketing/channel_roi', methods=['GET'])
def get_channel_roi():
    """API: 营销渠道ROI对比柱状图"""
    if campaign_data is None: return jsonify({"error": "营销活动数据未能加载"}), 500
    roi_by_channel = campaign_data.groupby('渠道')['投资回报率(ROI)'].mean().sort_values(ascending=False)
    result = {
        "channels": roi_by_channel.index.tolist(),
        "roi_values": roi_by_channel.values.tolist()
    }
    return jsonify(result)

@task2_bp.route('/api/marketing/campaign_funnel', methods=['GET'])
def get_campaign_funnel():
    """API: 活动效果漏斗图"""
    if campaign_data is None: return jsonify({"error": "营销活动数据未能加载"}), 500
    total_impressions = campaign_data['展示次数'].sum()
    total_interactions = campaign_data['互动次数'].sum()
    total_conversions = campaign_data['转化次数'].sum()
    result = [
        {"value": int(total_impressions), "name": "总展示"},
        {"value": int(total_interactions), "name": "总互动"},
        {"value": int(total_conversions), "name": "总转化"}
    ]
    return jsonify(result)